/*******************************************************************************
 * Copyright (c) 2005 Koji Hisano <hisano@users.sourceforge.net>
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Common Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/cpl-v10.html
 *
 * Contributors:
 *     Koji Hisano - initial API and implementation
 *******************************************************************************/
package jp.sf.mapswidgets;

/**
 * This class is the abstract superclass of all classes which represent overlays on the map.
 * <p>
 * See Google Maps API documentation [<a href="http://www.google.com/apis/maps/documentation/#GMarker_code_">Class Reference &gt; GMarker</a>] and [<a href="http://www.google.com/apis/maps/documentation/#GPolyline_code_">Class Reference &gt; GPolyline</a>].
 * </p>
 *
 * @see Marker
 * @see Polyline
 */
public abstract class Overlay {
	private static int count = 0;

	private int index;
	private GoogleMaps widget;

	Overlay() {
		index = count++;
	}
	
	public String toString() {
		return getId();
	}

	String getId() {
		return "" + index;
	}

	void init(GoogleMaps widgets) {
		if (!widgets.getOverlaysList().contains(this)) {
			String expressionToPrepare = getStatementsToPrepare();
			if (expressionToPrepare == null) {
				widgets.execute(getVariable() + " = " + getExpressionToCreate() + "; " + getVariable() + ".id = '" + getId() + "';");
			} else {
				widgets.execute(expressionToPrepare + " " + getVariable() + " = " + getExpressionToCreate() + "; " + getVariable() + ".id = '" + getId() + "';");
			}
			widgets.getOverlaysList().add(this);
			this.widget = widgets;
		}
	}

	void destroy(GoogleMaps widgets) {
		if (widgets.getOverlaysList().contains(this)) {
			widgets.execute("delete " + getVariable() + ";");
			widgets.getOverlaysList().remove(this);
			this.widget = null;
		}
	}
	
	String getStatementsToPrepare() {
		return null;
	}

	abstract String getExpressionToCreate();

	String getVariable() {
		return "map.elements[" + index + "]";
	}

	boolean isAdded() {
		return getWidget() != null;
	}

	GoogleMaps getWidget() {
		return widget;
	}
}
